/**
 * Copyright (c) 2017, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.sstech.member.core.timer;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 系统定时器管理
 * @author chenx
 * @date 2017年10月12日 上午11:35:58
 * @version 1.0
 */
public class SysTimerMngr extends Thread {
	
	private static final Logger mLog = LoggerFactory.getLogger(SysTimerMngr.class);
	
	/** 是否运行 */
	private boolean bIsRun = true;
	
	/** 高精准的单例 */
	private static SysTimerMngr instanceNicety = null;
	
	/**存放的定时器任务列表*/
	private List<BaseTimerTask> mTimerList= new ArrayList<BaseTimerTask>();
	
	/**
	 * 构造函数
	 */
	protected SysTimerMngr(){
	}
	
	/**
	 * 获得高精准的Timer管理器的实例
	 */
	public static synchronized SysTimerMngr getNicetyInstance() {
		
		if (instanceNicety == null) {
			
			instanceNicety = new SysTimerMngr();
			instanceNicety.setName("SYTimerManager.Nicety");
			instanceNicety.setPriority(4);
			instanceNicety.start();
		}
		
		return instanceNicety;
	}
	
	@Override
	public void run() {
		
		this.setName("SYTimerManager.Nicety");
		this.setPriority(4);
		mLog.debug("== 启动系统定时器线程 ==");
		
		while (bIsRun) {
			try{
				Thread.sleep(1000);
				synchronized(this.mTimerList) {
					long currTime = System.currentTimeMillis();
//					mLog.debug("运行定时器线程：" + mTimerList.size());
					for (int i = 0; i < mTimerList.size(); i++) {
						
						BaseTimerTask tmpTimer = mTimerList.get(i);
						if (tmpTimer.isNeedRemove) {
							this.removeTimer(tmpTimer.getTaskId());
						}
						
						if (tmpTimer != null && currTime >= tmpTimer.iNextTriggerTime) {
							
							if (!tmpTimer.execFinish) {
								// 没有设置执行完成则一直执行
								try{
									
									mLog.info( " 开始运行：[" + tmpTimer.taskId + " - " + tmpTimer.taskName +"]的计时监听");
									//触发定时任务
									tmpTimer.handlerTask();
	
									//计算下一次任务的执行时间
									//tmpTimer.iNextTriggerTime = System.currentTimeMillis() + tmpTimer.iPeriodTime;
									mLog.info(" 计时器：[" + tmpTimer.taskId + " - " + tmpTimer.taskName +"]执行完成。"+ "用时：[ "+ (System.currentTimeMillis() - currTime) +" ]毫秒");
								}catch(Exception ee){
									//tmpTimer.iNextTriggerTime = System.currentTimeMillis() + tmpTimer.iPeriodTime;
									mLog.error("执行计时任务：[" + tmpTimer.taskId + " - " + tmpTimer.taskName +"]失败，错误原因：" +ee.getMessage(), ee);
								}
							}
							
						}
					}
				}
			} catch(Exception e) {
				mLog.error("计时器线程故障："+ e.getMessage(), e);
			}
		}
		
	}
	
	/**
	 * 添加定时器
	 * @param timerTask         执行定时任务的类
	 */
	public void addTimer(BaseTimerTask timerTask) {
		
		synchronized(this.mTimerList) {
			mTimerList.add(timerTask);
		}		
	}
	
	/**
	 * 移除定时器
	 */
	public void removeTimer(String taskId){
		
		synchronized(this.mTimerList){
			for ( int i = 0 ; i < this.mTimerList.size() ; i++ ){
				BaseTimerTask tmpTimer = mTimerList.get(i);
				 //同一对象 
				if (tmpTimer != null && tmpTimer.taskId == taskId){
					mTimerList.remove(i);
					break;
				}
			}
		}
	}
}